//
//  YZMNewHomeViewController.m
//  YZMicroStock
//
//  Created by 王慕铁 on 2017/12/11.
//  Copyright © 2017年 cqjr. All rights reserved.
//

#import "YZMNewHomeViewController.h"
#import "HomeHeaderView.h"
#import "HomeFooterView.h"
#import "UIView+SubView.h"
#import "YZClient.h"
#import "YZMActivityModel.h"
#import "YZMHomeBannerModel.h"
#import <MJRefresh.h>
#import "YZMConfigureService.h"
#import "JSONBaseDeal.h"
#import "YZMAlertView.h"
#import <DateTools/DateTools.h>
#import "YZMWebViewService.h"

#define sYZMLastUpdateTimeDefault  @"YZMLastUpdateTimeDefault"
#define NavigationBarHeight  (NSInteger)(iPhoneX ? 88 : 64)
#define TabBarHeight  (NSInteger)(iPhoneX ? 83 : 49)

@interface YZMNewHomeViewController ()<HomeFooterViewDelegate>

@property (nonatomic , strong) HomeHeaderView*  homeHeaderView;
@property (nonatomic , strong) HomeFooterView*  homeFooterView;
@property (nonatomic , strong) UIScrollView*    scrollView;
@property (nonatomic , strong) UIImageView *imageViewRedEnvelope;
@property (nonatomic , strong) NSMutableArray *arrActivity;
@property (nonatomic , strong) MJRefreshNormalHeader* refreshHeader;


@end

@implementation YZMNewHomeViewController {
    
    BOOL _networkReadyFlag;//网络检测完成标志
    BOOL _unNeedCheckVersionFlag;//版本更新
    
    NSString *_downloadUrl;
    
}

- (HomeHeaderView *)homeHeaderView {
    if (!_homeHeaderView) {
        _homeHeaderView = [[HomeHeaderView alloc] init];
    }
    return _homeHeaderView;
}

- (HomeFooterView *)homeFooterView {
    if (!_homeFooterView) {
        _homeFooterView = [[HomeFooterView alloc] initWithY:self.homeHeaderView.bottom];
        _homeFooterView.delegate = self;
    }
    return _homeFooterView;
}

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - (iPhoneX ? 88 : 64))];
        
        _refreshHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(NetWork)];
        _refreshHeader.lastUpdatedTimeLabel.hidden = YES;
        _refreshHeader.stateLabel.textColor = [YZMAppStyle colorForGrayText];
        _refreshHeader.stateLabel.font = [YZMAppStyle mediumSizeFont];
        
        _scrollView.mj_header = _refreshHeader;
        
    }
    return _scrollView;
}

- (void)viewDidDisappear:(BOOL)animated {
    [self stop];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //    [_cycleScrollview adjustWhenControllerViewWillAppera];
    if (_networkReadyFlag || !kNetworkNotReachability) {
        
        _networkReadyFlag = YES;
        
        if (![[YZMConfigureService sharedService] isInTradeTimePeriods]) {
            
//            [self fetchTrendListData];
        }
//        [self fetchRankListData];
        [self start];
        
    }
    [self start];
    [self checkUpdate];
}

- (id)init{
    
    self = [super init];
    
    if (self) {
        self.title = @"首页";
        //        self.navigationItem.title = @"微策略";
        //获取info.plist文件内容
        NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
        self.navigationItem.title = infoDic[@"CFBundleDisplayName"];
        _arrActivity = [NSMutableArray array];

    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (YZMSWitchOn) {
        self.navigationItem.leftBarButtonItem = [YZMAppStyle leftBarItemWithImage:@"customer_service" target:self action:@selector(leftBarItemPressed:)];
        self.navigationItem.rightBarButtonItem = [YZMAppStyle rightBarItemWithImage:@"icon_guide" target: self action: @selector(rightBarItemPressed:)];
    }
    
    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubviews:@[self.homeHeaderView,self.homeFooterView]];
    
    _imageViewRedEnvelope = [[UIImageView alloc] init];
    _imageViewRedEnvelope.image = [UIImage imageNamed:@"redenvelope"];
    NSInteger originY = ScreenHeight - 86 - TabBarHeight - NavigationBarHeight;
    _imageViewRedEnvelope.frame = CGRectMake(ScreenWidth - 83 - 15, originY, 83, 86);
    [self.view addSubview:self.imageViewRedEnvelope];
    self.imageViewRedEnvelope.userInteractionEnabled = YES;
    //    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(changeFrame:)];
    //    [self.imageViewRedEnvelope addGestureRecognizer:pan];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushRedPackge:)];
    [self.imageViewRedEnvelope addGestureRecognizer:tap];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(end) name:@"endRefreshing" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:)
                                                 name:AFNetworkingReachabilityDidChangeNotification object:nil];
}



- (void)reachabilityChanged:(NSNotification *)note{
    
    if (!_networkReadyFlag) {
        
        _networkReadyFlag = YES;
        [self checkUpdate];
        
        if ([YZMHCMInstance.currentNavationCtroller.topViewController.class isSubclassOfClass:self.class]) {
            
            if (![[YZMConfigureService sharedService] isInTradeTimePeriods]) {
                
                [self NetWork];
            }
            [self NetWork];
            [self start];
            
        }
    }
}

- (void)checkUpdate{
    
    if (_unNeedCheckVersionFlag) {
        
        return;
    }
    
    _unNeedCheckVersionFlag = YES;
    [YZClient checkSoftwareUpdateSuccess:^(NSURLResponse *response, id responseObject){
        
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            [self updateLogicDeal:topModel.data];
        }else{
            
            _unNeedCheckVersionFlag = NO;
        }
        
    } failure:^(NSError *error) {
        
        _unNeedCheckVersionFlag = NO;
    }];
}

- (void)updateLogicDeal:(NSDictionary *)responseDic{
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *buildVersion = [infoDictionary objectForKey:@"CFBundleVersion"];
    
    if ([buildVersion integerValue] >= [JSONBaseDeal getIntValue:@"buildVersion" fromData:responseDic]) {
        
        return;
    }
    
    BOOL foreUpdateFlag = [JSONBaseDeal getIntValue:@"forceUpdate" fromData:responseDic]==1 ?YES:NO;
    
    _downloadUrl = [JSONBaseDeal getValue:@"downloadUrl" fromData:responseDic];
    
    if (foreUpdateFlag) {
        
        YZMAlertView *alertView = [YZMAlertView new];
        alertView.titleLabel.text = @"发现新版本";
        alertView.contentLabel.text = [JSONBaseDeal getValue:@"description" fromData:responseDic];
        alertView.cancelButton.hidden = YES;
        alertView.confirmHandle = ^(){
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_downloadUrl]];
            return NO;
        };
        
        [alertView showInView:YZMCMInstance.rootTabBarCtrl.view];
        return;
    }
    
    NSInteger lastUpdateDateInteger = 0;
    
    NSDate *lastUpdateDate = [[NSUserDefaults standardUserDefaults] objectForKey:sYZMLastUpdateTimeDefault];
    
    if (lastUpdateDate) {
        
        lastUpdateDateInteger = [[lastUpdateDate formattedDateWithFormat:@"yyyyMMdd"] integerValue];
    }
    
    if (lastUpdateDateInteger != 0) {
        
        NSInteger nowDateInteger = [[[NSDate date] formattedDateWithFormat:@"yyyyMMdd"] integerValue];
        
        if (nowDateInteger <= lastUpdateDateInteger) {
            
            return;
        }
    }
    
    YZMAlertView *alertView = [YZMAlertView new];
    alertView.titleLabel.text = @"发现新版本";
    alertView.contentLabel.text = [JSONBaseDeal getValue:@"description" fromData:responseDic];
    [alertView.sureButton setTitle:@"立即更新" forState:UIControlStateNormal];
    alertView.confirmHandle = ^(){
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_downloadUrl]];
        [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:sYZMLastUpdateTimeDefault];
        [[NSUserDefaults standardUserDefaults] synchronize];
        return YES;
    };
    alertView.cancleHandle = ^{
        
        [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:sYZMLastUpdateTimeDefault];
        [[NSUserDefaults standardUserDefaults] synchronize];
    };
    
    [alertView showInView:YZMCMInstance.rootTabBarCtrl.view];
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)pushRedPackge:(UITapGestureRecognizer *)tap{
    if (self.arrActivity.count == 0) {
        dispatch_group_t group = dispatch_group_create();
        dispatch_group_enter(group);
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [self fetchActivityList:group];
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            [hud setHidden:YES];
            [self configRedPackageDataAndPush];
        });
        return;
    }
    [self configRedPackageDataAndPush];
    
}

//活动列表
- (void)fetchActivityList:(dispatch_group_t)group{
    
    WS(ws)
    [YZClient Activity_activityListsuccess:^(NSURLSessionDataTask *task, id responseObject) {
        YZGeneralResultModel *topModel =responseObject;
        if (topModel.success) {
            [ws.arrActivity removeAllObjects];
            [ws.arrActivity addObjectsFromArray:topModel.data];
        }else{
            
            [topModel showMessage];
        }
        if (group) {
            dispatch_group_leave(group);
        }
    } failure:^(NSError *error) {
        [error yz_showMessage];
        if (group) {
            dispatch_group_leave(group);
        }
    }];
}

- (void)leftBarItemPressed:(UIButton *)sender{
    
    [YZMWebViewService openSuggestionCenter];
}

- (void)rightBarItemPressed:(UIButton *)sender{
    
    [YZMWebViewService openGuide];
}

- (void)configRedPackageDataAndPush{
    if (self.arrActivity.count > 0) {
        YZMActivityModel *model = self.arrActivity[0];
        NSDictionary *dic = @{@"bannerEvent":[model activityUrl], @"title":model.name, @"param":@{@"activityid":@(model.activityId)}};
        [YZMHomeBannerModel selectDirection:dic withLocal:YES];
    }
}

- (void)reloadView {
    [UIView animateWithDuration:0.5 animations:^{
        self.scrollView.contentSize = CGSizeMake(0, self.homeFooterView.bottom + 130);
    }];
   
}


- (void)stop {
    [self.homeFooterView stopTimer];
    [self.homeHeaderView stopTimer];
}

- (void)start {
    [self.homeFooterView startTimer];
    [self.homeHeaderView startTimer];
}

- (void)NetWork {
    [self.homeHeaderView NetWork];
    [self.homeFooterView NetWork];
}

- (void)end {
    [_refreshHeader endRefreshing];
}


@end
